package com.bw.good


import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.good.R
import com.bawei.good.databinding.ActivityGoodBinding
import com.bw.good.adapter.GoodListAdapter
import com.bw.good.entity.GoodEntity
import com.bw.good.intent.GoodViewIntent
import com.bw.good.state.GoodUiState
import com.bw.good.vm.GoodViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * 20250215 游戏鸿蒙-i视频-05-商品详情-李秭韶
 */
@Route(path = RoutePath.PATH_GOOD_PAGE)
@AndroidEntryPoint
class GoodActivity : BaseMviActivity<ActivityGoodBinding>() {


    private val mViewModel: GoodViewModel by viewModels()

    private lateinit var mGoodListAdapter: GoodListAdapter

    private val goodList = mutableListOf<GoodEntity>()

    private var categoryId: Int = 0
    private var currentPage: Int = 1
    private var pageSize: Int = 20


    override fun getLayoutId(): Int = R.layout.activity_good

    override fun initViews() {
        mGoodListAdapter = GoodListAdapter(goodList)
        mDataBinding.rvGoodList.apply {
            layoutManager = GridLayoutManager(context,1)
            adapter = mGoodListAdapter
        }

        //点击跳转到商品详情页面
        mGoodListAdapter.setItemClickListener(object : GoodListAdapter.GoodItemClickListener{
            override fun onItemClickChildClick(v: View, position: Int, entity: GoodEntity) {
                if (v.id == R.id.tv_go_buy) {
                    ARouter.getInstance().build(RoutePath.PATH_GOOD_DETAIL_PAGE).withSerializable("entity", goodList[position]).navigation()
                }
            }
        })


    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(GoodViewIntent.LoadGoodList(categoryId, currentPage, pageSize))
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect {
            when(it) {
                is GoodUiState.LoadGoodListFail -> showToastMsg(it.msg)
                is GoodUiState.LoadGoodListSuccess -> {
                    goodList.clear()
                    goodList.addAll(it.list)
                    mGoodListAdapter.notifyDataSetChanged()
                    Log.i("TagA", it.list.toString())
                }
                else -> {}
            }
        }
    }

}